<template>
    <div :id="`checkcitybox-${name}`" :ref="`checkcitybox-${name}`" :class="['checkcity', {'checkcityclick': show}]" @click="checkme" style="width:200px">
<!--        <input style="display:none" :value="modelValue" >-->
        <span class="checkcity-value" v-if="modelValue[0]">{{ city_str.join('/') }}</span>
        <span class="checkcity-placeholder" v-else>请选择省、市、区</span>
        <Icon v-if="modelValue[0]" class="close" type="ios-arrow-down"  @click.stop @click="close"></Icon>
        <Icon v-else type="ios-arrow-down"></Icon>
        <div :ref="`checkcity-${name}`" :style="style">
            <div class="checkcity-fixed" v-if="show" @click="show=false"></div>
            <div class="checkcity-con" @click.stop v-if="show">
                <Tabs v-model="citys" name="city" :animated="false">
                    <TabPane label="省" name="province" tab="city">
                        <jgoptioncity type="province" :value="modelValue" @checkOption="checkProvince"></jgoptioncity>
                    </TabPane>
                    <TabPane label="市" name="city" :disabled="!modelValue[0]" tab="city">
                        <jgoptioncity  type="city" :value="modelValue" @checkOption="checkCity"></jgoptioncity>
                    </TabPane>
                    <TabPane label="区县" name="county" :disabled="!modelValue[2] && !modelValue[1]" tab="city">
                        <jgoptioncity type="county" :value="modelValue" @checkOption="checkCounty"></jgoptioncity>
                    </TabPane>
                </Tabs>
            </div>
        </div>
    </div>
</template>
<script>
    import { commonprovincelist } from '@/api/city.js';
    import jgoptioncity from './optioncity';
    export default {
        components: { jgoptioncity },
        props: {
            modelValue: {
                type: [Array],
                required: true,
                default: function() {
                    return [];
                }
            },
            name: {
                type: [String],
                default: ''
            }
        },
        // setup(props, context) {
        //     const closeAction = () => {
        //         context.emit('update:model-value', this.values);
        //         console.log('closeAction');
        //     };
        //     return {
        //         closeAction,
        //     };
        // },
        watch:{
            modelValue(newVal){
                this.values=newVal;
                this.getCityStrArr();
            } 
        },
        data() {
            return {
                show: false,
                citys: 'province',// province、city、county
                values: [],// 选中cityid
                city_str: [],// 选中城市名
                datas: [],
                style: {},
                check: false,
            };
        },
        mounted() {
            this.askData();
        },
        methods: {
            checkme() {
                if(!this.modelValue[0])
                    this.citys = 'province';
                else if(!this.modelValue[1])
                    this.citys = 'city';
                else
                    this.citys = 'county';

                this.show = true;
                this.$nextTick(() => {
                    this.check = true;
                    const body = document.querySelector('body');
                    let checkcity = this.$refs[`checkcity-${this.name}`];
                    if(body.append) {
                        body.append(checkcity);
                    }else {
                        body.appendChild(checkcity);
                    }
                    this.style = { top: 0, bottom: 0, position: 'absolute' };
                    let width = document.body.clientWidth; // 1350
                    let height = document.body.clientHeight; // 937
                    var box = this.$refs[ `checkcitybox-${this.name}`].getClientRects();
                    if(height - box[0].bottom < 454 && width - box[0].left < 400) {
                        this.style = { left: `${box[0].left - 200}px`, top: `${box[0].top - 464}px`, position: 'absolute' };
                    }else if(height - box[0].bottom < 454) {
                        this.style = { left: `${box[0].left}px`, top: `${box[0].top - 464}px`, position: 'absolute' };
                    }else if(width - box[0].left < 400) {
                        this.style = { left: `${box[0].left - 200}px`, top: `${box[0].top + 30}px`, position: 'absolute' };
                    }else {
                        this.style = { left: `${box[0].left}px`, top: `${box[0].top + 30}px`, position: 'absolute' };
                    }
                });
            },
            close() {
                this.citys = 'province';
                this.city_str = [];
                this.sendEmitModelValue([]);
            },
            askData() {
                this.values = this.modelValue;
                // console.log(this.modelValue, this.name,'modelValue')
                // 省市区列表
                commonprovincelist().then(res => {
                    localStorage.setItem('citytime',  this.$Date().format('YYYY-MM-DD'));
                    localStorage.setItem('cityarray', JSON.stringify(res.data));
                    // 城市映射
                    let cityMap = {};
                    res.data.forEach(province => {
                        let cityItem = {};
                        province.children.forEach(city => {
                            let countyItme = {};
                            city.children.forEach(county => {
                                countyItme[county.value] = county;
                            })

                            cityItem[city.value] = {
                                value: city.value,
                                label: city.label,
                                children: countyItme,
                            }
                        })
                        cityMap[province.value] = {
                            value: province.value,
                            label: province.label,
                            children: cityItem,
                        }
                    })
                    localStorage.setItem('cityarray_map', JSON.stringify(cityMap));

                    this.getCityStrArr();
                });
            },
            getCityStrArr() {
                let cityMapStr = localStorage.getItem('cityarray_map');
                let cityMap = JSON.parse(cityMapStr);
                if (this.modelValue.length > 0) {
                    this.city_str[0] = cityMap[this.modelValue[0]].label;
                    if (this.modelValue.length > 1) {
                        this.city_str[1] = cityMap[this.modelValue[0]].children[this.modelValue[1]].label;
                        if (this.modelValue.length > 2) {
                            this.city_str[2] = cityMap[this.modelValue[0]].children[this.modelValue[1]].children[this.modelValue[2]].label;
                        }
                    }
                }
            },
            // 选择省
            checkProvince(item) {
                this.values = [];
                this.city_str = [];
                if (item) {
                    this.values.push(item.value);
                    this.city_str.push(item.label);
                    this.citys = 'city';
                } else {
                    this.citys = 'province';
                }
                this.sendEmitModelValue(this.values);
            },
            // 选择市
            checkCity(item) {
                if (item) {// 选中
                    this.values[1] = item.value;
                    this.city_str[1] = item.label;
                    this.citys = 'county';
                } else {// 未选中
                    this.values.splice(1);
                    this.city_str.splice(1);
                    this.citys = 'city';
                }
                this.sendEmitModelValue(this.values);
            },
            // 选择区
            checkCounty(item) {
                if (item) {// 选中
                    this.values[2] = item.value;
                    this.city_str[2] = item.label;
                    this.show = false;
                } else {// 未选中
                    this.values.splice(2);
                    this.city_str.splice(2);
                }
                this.citys = 'county';
                this.sendEmitModelValue(this.values);
            },
            // 通知父级
            sendEmitModelValue(value) {
                // console.log(value,'city')
                this.$emit('update:model-value', value);
            },
        }
    };
</script>
<style lang="less" scoped>
.checkcityclick {
    .ivu-icon {
        transform: translateY(-50%) rotate(180deg)!important;
        display: inline-block;
    }
}
.checkcity {
    height: 32px;
    position: relative;
    display: block;
    box-sizing: border-box;
    outline: none;
    user-select: none;
    cursor: pointer;
    position: relative;
    background-color: #fff;
    border-radius: 4px;
    border: 1px solid #dcdee2;
    transition: all 0.2s ease-in-out;
    &-placeholder {
        display: block;
        height: 30px;
        line-height: 30px;
        font-size: 14px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        padding-left: 8px;
        padding-right: 24px;
        color: #999;
    }
    &-value{
        display: block;
        height: 30px;
        line-height: 30px;
        font-size: 14px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        padding-left: 8px;
        padding-right: 24px;
    }
    &-fixed{
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        margin: auto;
        z-index: 10000;
    }
    &-con{
        position: absolute;
        width: 400px;
        background-color: #fff;
        z-index: 10001 !important;
        margin: 5px 0;
        height: 454px;
        padding: 16px;
        background-color: #fff;
        box-sizing: border-box;
        border-radius: 4px;
        box-shadow: 0 1px 6px rgba(0, 0, 0, .2);
    }
    &-cons{
        position: absolute;
        padding: 16px;
        width: 400px;
        background-color: #fff;
        z-index: 10001;
        margin: 5px 0;
        height: 454px;
        padding: 16px;
        background-color: #fff;
        box-sizing: border-box;
        border-radius: 4px;
        box-shadow: 0 1px 6px rgba(0, 0, 0, .2);
    }
    .close:hover{
        &:before{
            content: '\f177'
        }
    }
    .ivu-icon-ios-arrow-down {
        position: absolute;
        top: 50%;
        right: 8px;
        line-height: 1;
        transform: translateY(-50%);
        font-size: 14px;
        color: #808695;
        transition: all 0.2s ease-in-out;
    }
}
</style>
